package com.xaicode.auth.config.xss;

import cn.hutool.core.util.StrUtil;
import com.xaicode.auth.config.properties.SystemProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;

/**
 * 注入过滤器配置
 * 
 * @date 2024/12/9
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({SystemProperties.class})
public class XssConfig {

    @Bean
    @ConditionalOnProperty(value = "system.xss.enabled", havingValue = "true", matchIfMissing = true)
    public FilterRegistrationBean<XssFilter> xssFilterRegistration(SystemProperties systemProperties) {
        log.info("注入 XssFilter");

        // 创建 XSS 注入过滤器
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(StrUtil.splitToArray(systemProperties.getXss().getUrlPatterns(), ","));
        registration.setName("xssFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);

        // 配置忽略过滤的地址
        //Map<String, String> initParameters = new HashMap<>();
        //initParameters.put("excludes", StrUtil.blankToDefault(systemProperties.getXss().getExcludes(), ""));
        //registration.setInitParameters(initParameters);
        if (StrUtil.isNotBlank(systemProperties.getXss().getExcludes())) {
            registration.addInitParameter("excludes", systemProperties.getXss().getExcludes());
        } else {
            registration.addInitParameter("excludes", "");
        }

        return registration;
    }

}
